package com.xiaoshuidi.cloud.module.finance.controller.admin.finance;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.PdfWriter;
import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.framework.common.pojo.PageResult;
import com.xiaoshuidi.cloud.framework.datapermission.core.annotation.DataPermission;
import com.xiaoshuidi.cloud.framework.excel.core.util.ExcelUtils;
import com.xiaoshuidi.cloud.module.finance.controller.admin.finance.vo.transfer.FinancePaymentChangeLogExcelVO;
import com.xiaoshuidi.cloud.module.finance.controller.admin.finance.vo.transfer.FinancePaymentChangeLogPageReqVO;
import com.xiaoshuidi.cloud.module.finance.controller.admin.finance.vo.transfer.FinancePaymentChangeLogVO;
import com.xiaoshuidi.cloud.module.finance.controller.admin.finance.vo.transfer.FinancePaymentChangeUpdateVO;
import com.xiaoshuidi.cloud.module.finance.convert.finance.FinanceConvert;
import com.xiaoshuidi.cloud.module.finance.enums.order.BankTransferStatusEnum;
import com.xiaoshuidi.cloud.module.finance.service.finance.FinancePaymentChangeLogService;
import com.xiaoshuidi.cloud.module.finance.util.pdf.PdfUtils;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 管理后台 - 打款变更记录
 */
@Tag(name = "管理后台 - 打款变更记录")
@RestController
@RequestMapping("/finance/change-log")
public class FinancePaymentChangeLogController {

    @Resource
    private FinancePaymentChangeLogService financePaymentChangeLogService;

    /**
     * 部门权限分页
     *
     * @param reqVO
     * @return
     */
    @GetMapping("/dept-page")
    public CommonResult<PageResult<FinancePaymentChangeLogVO>> deptPage(FinancePaymentChangeLogPageReqVO reqVO) {
        return CommonResult.success(financePaymentChangeLogService.selectLogPage(reqVO));
    }

    /**
     * 部门权限导出
     *
     * @param reqVO
     * @return
     */
    @GetMapping("/dept-export")
    public void deptExport(HttpServletResponse response, FinancePaymentChangeLogPageReqVO reqVO) throws IOException {
        reqVO.setPageSize(100);
        PageResult<FinancePaymentChangeLogVO> pageResult = financePaymentChangeLogService.selectLogPage(reqVO);
        ExcelUtils.write(response, "修改单.xlsx", "明细", FinancePaymentChangeLogExcelVO.class, pageResult,
                FinanceConvert.INSTANCE::convertLogExcelList, (pageNo) -> {
                    reqVO.setPageNo(pageNo);
                    return financePaymentChangeLogService.selectLogPage(reqVO);
                });
    }

    /**
     * 无权限分页
     *
     * @param reqVO
     * @return
     */
    @GetMapping("/page")
    @DataPermission(enable = false)
    public CommonResult<PageResult<FinancePaymentChangeLogVO>> page(FinancePaymentChangeLogPageReqVO reqVO) {
        return CommonResult.success(financePaymentChangeLogService.selectLogPage(reqVO));
    }

    /**
     * 无权限分页导出
     *
     * @param reqVO
     * @return
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response, FinancePaymentChangeLogPageReqVO reqVO) throws IOException {
        reqVO.setPageSize(100);
        PageResult<FinancePaymentChangeLogVO> pageResult = financePaymentChangeLogService.selectLogPage(reqVO);
        ExcelUtils.write(response, "修改单.xlsx", "明细", FinancePaymentChangeLogExcelVO.class, pageResult,
                FinanceConvert.INSTANCE::convertLogExcelList, (pageNo) -> {
                    reqVO.setPageNo(pageNo);
                    return financePaymentChangeLogService.selectLogPage(reqVO);
                });
    }

    /**
     * 查看详情
     *
     * @param id
     * @return
     */
    @DataPermission(enable = false)
    @GetMapping("/get-by-id")
    public CommonResult<FinancePaymentChangeLogVO> getById(@RequestParam("id") Long id) {
        return CommonResult.success(financePaymentChangeLogService.getById(id));
    }

    /**
     * 获取打款编辑详情
     *
     * @param id
     * @return
     */
    @DataPermission(enable = false)
    @GetMapping("/get-by-id-update-view")
    public CommonResult<FinancePaymentChangeUpdateVO> getByIdUpdateView(@RequestParam("id") Long id) {
        return CommonResult.success(financePaymentChangeLogService.getByIdUpdateView(id));
    }

    /**
     * 变更打款
     *
     * @param changeUpdateVO
     * @return
     */
    @DataPermission(enable = false)
    @PostMapping("/change-payment-transfer")
    public CommonResult<Boolean> changePaymentTransfer(@RequestBody FinancePaymentChangeUpdateVO changeUpdateVO) {
        return CommonResult.success(financePaymentChangeLogService.changePaymentTransfer(changeUpdateVO));
    }

    /**
     * 打印单据
     *
     * @param ids
     * @param response
     * @throws Exception
     */
    @DataPermission(enable = false)
    @GetMapping("/pdf")
    public void pdf(@RequestParam("ids") String ids, HttpServletResponse response) throws Exception {
        List<FinancePaymentChangeLogVO> list = financePaymentChangeLogService.getByIds(
                Arrays.asList(ids.split(",")).stream().map(Long::valueOf).collect(Collectors.toList()));
        Font header = PdfUtils.getFont();
        header.setSize(18);
        header.setStyle(Font.FontStyle.BOLD.getValue());
        Font bold = PdfUtils.getFont();
        bold.setStyle(Font.FontStyle.BOLD.getValue());

        PdfUtils.PdfDoc doc = PdfUtils.newPdfDoc();
        OutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(String.format("变更单_%s" +
                ".pdf", DateUtil.format(new Date(), "yyyyMMddHHmmss")), "UTF-8"));
        response.setContentType("application/pdf;charset=UTF-8");

        PdfWriter.getInstance(doc.getDoc(), os);
        doc.open();
        if (CollectionUtils.isEmpty(list)) {
            doc.addParagraph("未找到变更信息");
            doc.close();
            os.close();
            return;
        }

        for (FinancePaymentChangeLogVO vo : list) {
            doc.addParagraph(DateUtil.format(new Date(), "yyyy/MM/dd"));
            doc.addTable(4, tb -> {
                        // 主表单信息
                        tb.addCell("付款信息修改记录", 4, header, cell -> {
                                    cell.setPaddingTop(5);
                                    cell.setPaddingBottom(10);
                                })
                                .addCell("基本信息", 4, bold, Element.ALIGN_LEFT)
                                .addCell("相关单号").addCell(vo.getBizNo(), 3)
                                .addCell("业务类别", vo.getBusinessType(), "门店",
                                        vo.getDepartment())
                                .addCell("合同编号", vo.getContractNo(), "收款方", vo.getPayeeType())
                                .addCell("付款金额", vo.getPayAmount().toString(), "状态",
                                        BankTransferStatusEnum.getDesc(vo.getStatus()))
                                .addCell("付款成功时间"
                                        , ObjectUtil.isNotNull(vo.getPayTime()) ? DateUtil.format(vo.getPayTime(),
                                                "yyyy:MM:dd HH:mm:ss") : ""
                                        , "单据创建时间"
                                        , ObjectUtil.isNotNull(vo.getTransCreateTime()) ?
                                                DateUtil.format(vo.getTransCreateTime(), "yyyy:MM:dd HH:mm:ss") : "")
                                .addCell("修改人", vo.getChangeOperator(), "修改时间", ObjectUtil.isNotNull(vo.getUpdateTime())
                                        ? DateUtil.format(vo.getUpdateTime(), "yyyy:MM:dd HH:mm:ss") : "")
                                .addCell("修改前付款信息", 4, bold, Element.ALIGN_LEFT)
                                .addCell("付款单号").addCell(vo.getNumber(), 3)
                                .addCell("收款人", vo.getPayeeName(), "手机号", vo.getPayeeMobile())
                                .addCell("银行卡号", vo.getPayeeBankAccount(), "所属银行", vo.getPayeeBank())
                                .addCell("所属支行", vo.getPayeeBankBranch(), "支行行号", vo.getPayeeBankCode())

                                .addCell("修改后付款信息", 4, bold, Element.ALIGN_LEFT)
                                .addCell("付款单号").addCell(vo.getAfterNumber(), 3)
                                .addCell("收款人", vo.getAfterPayeeName(), "手机号", vo.getAfterPayeeMobile())
                                .addCell("银行卡号", vo.getAfterPayeeBankAccount(), "所属银行", vo.getAfterPayeeBank())
                                .addCell("所属支行", vo.getAfterPayeeBankBranch(), "支行行号", vo.getAfterPayeeBankCode())
                        ;

                        tb.options(t -> {
                            t.setWidthPercentage(100);
                            try {
                                t.setWidths(new float[]{18f, 32f, 18f, 32f});
                            } catch (DocumentException ignore) {
                            }
                        });
                    }
            );
            doc.getDoc().newPage();
        }
        doc.close();
        os.close();
    }

}
